package com.msb.dongbao.portal.web.util;


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

public class HttpParamUtils {

    public static SortedMap<String, String> getAllparams(HttpServletRequest httpServletRequest) throws IOException {
        //获取url上的参数
        Map<String, String> urlParams = getUrlParams(httpServletRequest);
//        System.out.println("url参数:"+urlParams);
        // 获取 body上的参数
        Map<String, String> bodyParams = getBodyParams(httpServletRequest);
        SortedMap<String, String> allMap = new TreeMap<>();
        if (urlParams!=null&&!urlParams.isEmpty()) {
            for (Map.Entry entry : urlParams.entrySet()) {
                allMap.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        if (bodyParams!=null&&!bodyParams.isEmpty()) {
            for (Map.Entry entry : bodyParams.entrySet()) {
                allMap.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        return allMap;
    }

    private static Map<String, String> getBodyParams(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        //读取流
        String s = "";
        while ((s = reader.readLine()) != null) {
            sb.append(s);
        }
        //转map
        Map map = JSONObject.parseObject(sb.toString(), Map.class);
//        System.out.println("map="+map);
        return map;
    }

    /***
     * 获取url中的参数
     * @param request
     * @return
     */
    private static Map<String, String> getUrlParams(HttpServletRequest request) {
        String queryParam = "";
        try {
            if (!StringUtils.isBlank(request.getQueryString())) {
                queryParam = URLDecoder.decode(request.getQueryString(), "utf-8");
                Map<String, String> result = new HashMap<>();
                String[] split = queryParam.split("&");
                for (String s : split) {
                    int i = s.indexOf("=");
                    result.put(s.substring(0, i), s.substring(i + 1));
                }
                return result;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
